package com.seele.tigerwallet.wallet;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.seele.tigerwallet.utils.Constants;
import com.seele.tigerwallet.utils.SeeleFileMap;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class WalletManager {
    private EthWallet mCurrentEthWallet;
    private List<EthWallet> mEthWallet = new ArrayList<EthWallet>(); // key是name
    private static WalletManager instance = new WalletManager();
    private static final String TAG = "WalletManager";


    public static WalletManager getInstance() {
        return instance;
    }

    private WalletManager(){
       jsonToList();
    }


    public List<EthWallet> getEthWallet() {
        return mEthWallet;
    }

    public void addEthWallet(EthWallet wallet) {
        jsonToList();
        mEthWallet.add(wallet);
        listToJson();
    }

    public EthWallet getCurrentEthWallet() {
        if (mCurrentEthWallet == null) {
            String currentJson = SeeleFileMap.getString(Constants.KEY_WALLET_CURRENT);
            mCurrentEthWallet = new Gson().fromJson(currentJson, EthWallet.class);
        }
        Log.i(TAG, "current wallet:" + mCurrentEthWallet.toString());
        return mCurrentEthWallet;
    }

    public void setCurrentEthWallet(EthWallet wallet) {
        String json = new Gson().toJson(wallet);
        Log.i(TAG, "current wallet json:" + json);
        SeeleFileMap.putString(Constants.KEY_WALLET_CURRENT, json);
        this.mCurrentEthWallet = wallet;

    }

    private String listToJson() {
        String json = new Gson().toJson(mEthWallet);
        SeeleFileMap.putString(Constants.KEY_WALLET_ALL, json);
        Log.i(TAG, "wallet json:" + json);
        return json;
    }

    private List<EthWallet> jsonToList() {
        String jsonWallet = SeeleFileMap.getString(Constants.KEY_WALLET_ALL);
        Log.i(TAG, "jsonWallet:" + jsonWallet);

        Type listType = new TypeToken<ArrayList<EthWallet>>(){}.getType();
        ArrayList<EthWallet> customList = new ArrayList<EthWallet>();
        customList = new Gson().fromJson(jsonWallet, listType);
        if (customList == null) {
            return customList;
        }
        mEthWallet.addAll(customList);
        for (int i = 0; i < customList.size(); i++) {
            String wallet = customList.get(i).toString();
            Log.i(TAG, "ethWallet:" + wallet);
        }
        return customList;
    }

}
